<!doctype html>
<html>

	<head>
		<meta charset="utf-8">
		<title>登录</title>
		<meta name="viewport"
			content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
		<link href="css/mui.css" rel="stylesheet" />
	</head>

	<body>
		<header class="mui-bar mui-bar-nav">
			<h1 class="mui-title">登录</h1>
		</header>
		<div class="mui-content">
			<form class="mui-input-group" id="input_example">
				<div class="mui-input-row">
					<label>用户名</label>
					<input type="text" name="username"  class="mui-input-clear" placeholder="请输入用户名">
				</div>
				<div class="mui-input-row">
					<label>密码</label>
					<input type="password" name="password"  class="mui-input-password" placeholder="请输入密码">
				</div>
				<div class="mui-button-row">
					<button type="button" class="mui-btn mui-btn-primary">确认</button>
					<button type="button" class="mui-btn mui-btn-danger">取消</button>
				</div>
			</form>
		</div>
		<script src="js/mui.js"></script>
		<script type="text/javascript">
			mui.init()
			mui(".mui-button-row").on("tap",'.mui-btn-primary', function() {
						var check = true;
						// 验证密码是否为空
						mui("#input_example input").each(function() {
							//若当前input为空，则alert提醒 
							if (!this.value || this.value.trim() == "") {
								var label = this.previousElementSibling;
								mui.alert(label.innerText + "不允许为空");
								check = false;
								return false;
							}
						}); //校验通过，继续执行业务逻辑 
						
						// 通过id获得用户名、密码
											
						var username = document.querySelector('input[name="username"]').value;
						var password = document.querySelector('input[name="password"]').value;
						
						// 发送请求
						mui.ajax('http://localhost:8000/api/users/login', {
							data: {
								userName: username,
								password: password
							},
							dataType: 'json', //服务器返回json格式数据	
							type: 'post', //HTTP请求类型
							timeout: 10000, //超时时间设置为10秒；
							success: function(data) {
								if (data.code == 0) {
									mui.alert('登录成功！')
									// 存储当前token
									localStorage.setItem('token', data.result.token)
									// 跳转到首页
									mui.openWindow({
										url: 'index.html'
									})
								} else {
									mui.alert('登录失败！',data.message)
									// 清除token
									localStorage.removeItem('token')
																
									
									// 重新登录
									mui.openWindow({
										url: 'login.html'
									})
								}
							},	
							error: function(xhr, type, errorThrown) {
								//异常处理；
								mui.alert('登录失败！')
							}
							
						});
								
								
					});
		</script>
	</body>

</html>